const fs = require('fs');
const path = require('path');


function createDir(url) {
  return new Promise((resolve, reject) => {
    fs.mkdir(path.resolve(__dirname, `./api/${url}`), (err, data) => {
      if (err) {
        resolve('');
      } else {
        resolve(2, data);
      }
    });
  });
}
const mock = function (app) {
  app.use(/\/api/, async (req, res) => { // 获取
    // const fspath = req.path.split('/');
    req.path=req.path.replace(/dev\-api/g,"")
    req.path=req.path.replace(/\//g,"+")
    // const url = `${path.resolve(__dirname, `./api/${fspath[2]}/${fspath[3]}`)}.json`;
    const url = `${path.resolve(__dirname, `./api/${req.path}`)}.json`;
    const data = await fs.readFileSync(url);
    res.send(data);
  });
  app.use(/\/createMock/, async (req, res) => { // 设置
    console.log(req.body);
    const data = JSON.stringify(req.body);
    let furl=req.path.toString()
    furl=furl.replace(/dev\-api/g,"")
    furl=furl.replace(/\//g,"+")
    console.log(furl)
    // const fspath = req.path.split('/');
    // const type = await createDir(fspath[2]);
    // const url = `${path.resolve(__dirname, `./api/${fspath[2]}/${fspath[3]}`)}.json`;
    const url = `${path.resolve(__dirname, `./api/${furl}`)}.json`;
    fs.writeFileSync(url, data);
    res.send({ msg: data });
  });
};

module.exports = mock;
